package service.impl;

import service.UserService;
import ssm.dao.impl.UserDaoImpl;
import ssm.pojo.User;
import util.MD5Utils;
import util.MailUtils;

import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    @Override
    public User foundUByName(String name) {
        try {
            UserDaoImpl userDao = new UserDaoImpl();
            User user = userDao.foundUName(name);
            if (user != null) {
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void registerUser(User user) {
        try {
            UserDaoImpl userDao = new UserDaoImpl();
            int i = userDao.addUser(user);

            String text = "欢迎注册,请您<a href='http://localhost:8080/11_22_war/user?methodName=active&code=" + user.getCode() + "'>点击激活</a>";
            MailUtils.sendMail(user.getEmail(), text, "用户激活邮件");

        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

    @Override
    public User founduByCode(String code) {
        try {
            UserDaoImpl userDao = new UserDaoImpl();
            User user = userDao.founduByCode(code);
            if (user == null) {
                return null;
            }
            user.setState(1);
            userDao.updateUser(user);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User login(String username, String password) {
        try {
            String s = MD5Utils.md5(password);
            UserDaoImpl userDao = new UserDaoImpl();
            User u = userDao.loginUser(username);
            if (u != null) {
                if (u.getPassword().equals(s)) {
                    return u;
                } else {
                    return null;
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public User foundUByNP(String username, String password) {
        try {
            UserDaoImpl userDao = new UserDaoImpl();
            User u = userDao.loginUser(username);
            if (u.getPassword().equals(password)) {
                return u;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
